package at.jku.ssw.fortress.ui.wizard;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;

import at.jku.ssw.fortress.builder.FortressBuilder;
import at.jku.ssw.fortress.builder.FortressNature;

public class NewProjectWizard extends BasicNewResourceWizard {
	private NewProjectWizardPage page;

	public NewProjectWizard() {
		setNeedsProgressMonitor(true);
	}

	public void addPages() {
		setWindowTitle("New file");
		page = new NewProjectWizardPage();
		addPage(page);
	}

	public boolean performFinish() {
		final String projectName = page.getProjectName();
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(projectName, monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			realException.printStackTrace();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}

	private void doFinish(String projectName, IProgressMonitor monitor)  throws CoreException {
		monitor.beginTask("Creating " + projectName, 2);
		monitor.setTaskName("Creating project hierarchy...");
		IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
		if(newProject.exists()) {
			throwCoreException("Project \"" + projectName + "\" already exists.");
		}
		newProject.create(monitor);
		monitor.worked(1);
		
		monitor.setTaskName("Opening project...");
		newProject.open(monitor);
		FortressNature.appendTo(newProject);
		monitor.worked(1);
	}
	
	private void throwCoreException(String message) throws CoreException {
		IStatus status =
			new Status(IStatus.ERROR, "testplugin", IStatus.OK, message, null);
		throw new CoreException(status);
	}

}